import { isArray } from './prototype.js'

let timer
let pre = 0
/**
 * 深度拷贝
 * @param {any} data
 */
export function deepCopy (data) {
  const t = isArray(data) ? 'array' : typeof data
  let o

  if (t === 'array') {
    o = []
  } else if (t === 'object') {
    o = {}
  } else {
    return data
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(deepCopy(data[i]))
    }
  } else if (t === 'object') {
    for (const i in data) {
      o[i] = deepCopy(data[i])
    }
  }
  return o
}

/**
 * 延迟执行
 * @param ms
 * @returns {Promise<any>}
 */
export function timeout (ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

/**
 * 防抖函数
 * @param {Function} event 执行事件
 * @param {Number} time 延迟时间
 */
export function debounce (event, time) {
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      event.apply(this, args)
    }, time)
  }
}

/**
 * 节流函数
 * @param {Function} event 执行事件
 * @param {Number} time 延迟时间
 */
export function throttle (event, time) {
  return function (...args) {
    if (Date.now() - pre > time) {
      clearTimeout(timer)
      timer = null
      pre = Date.now()
      event.apply(this, args)
    } else if (!timer) {
      timer = setTimeout(() => {
        // event.apply(this, args)
      }, time)
    }
  }
}

/**
 * 字节大小转换
 * @param {*} size
 * @returns
 */
export function fileSize (size) {
  if (typeof size !== 'number') return '0K'
  if (size > 1048576) size = (size / 1048576).toFixed(2) + 'M'
  else if (size > 1024) size = (size / 1024).toFixed(2) + 'K'
  return size
}
